/*******************************************************************
		Author		:	
		************************************************************
		Comment		:	
		************************************************************
		Log			::
		Create		:	2011-01-01
		Change		:	2011-01-01
					:	
********************************************************************/
#include "socket.h"
#include <stdio.h>

namespace wx_net
{
	UDPSocket::UDPSocket(const uint16 port,const char* addrIP)
	{
		m_socket = ::socket(AF_INET,SOCKET_DGRAM,IPPROTO_UDP);
		if( m_socket == INVALID_SOCKET )
			printf("init socket failed");
		memset(m_addr,0,sizeof(m_addr));
		m_addr.sin_family = AF_INET;
		m_addr.sin_addr.s_addr = addrIP ? ::inet_addr(addrIP) : ::htonl(INADDR_ANY);
		m_addr.sin_port = htons(port);
	}
	retcode_t UDPSocket::Close()
	{
		retcode_t rt = SUCCESS;
#ifdef _WIN32
		if(::closesocket(m_socket) == SOCKET_ERROR)
#else
		if(::close(m_socket) == SOCKET_ERROR)
#endif
			rt = GetLastError();
		return rt;
	}
	retcode_t UDPSocket::Bind()
	{
		retcode_t rt = SUCCESS;
		if( ::bind(m_socket,(SA*)&m_addr,sizeof(m_addr)) == SOCKET_ERROR )
			rt = GetLastError();
		return rt;
	}

	TCPSocket::TCPSocket(const uint16 port,const char* addrIP)
	{
		m_socket = ::socket(AF_INET,SOCKET_STREAM,IPPROTO_TCP);
		if( m_socket == INVALID_SOCKET )
			printf("init socket failed");
		memset(m_addr,0,sizeof(m_addr));
		m_addr.sin_family = AF_INET;
		m_addr.sin_addr.s_addr = addrIP ? ::inet_addr(addrIP) : ::htonl(INADDR_ANY);
		m_addr.sin_port = htons(port);
	}
	TCPSocket::~TCPSocket()
	{
		if( (retcode_t rt = Close()) != SUCCESS )
			printf("close socket failed! error = %d",rt);
	}
	retcode_t TCPSocket::Close()
	{
		retcode_t rt = SUCCESS;
#ifdef _WIN32
		if(::closesocket(m_socket) == SOCKET_ERROR)
#else
		if(::close(m_socket) == SOCKET_ERROR)
#endif
			rt = GetLastError();
		return rt;
	}
	retcode_t TCPSocket::Connect()
	{
		retcode_t rt = SUCCESS;
		if(::connect(m_socket,(SA*)&m_addr,sizeof(m_addr)) == SOCKET_ERROR )
			rt = GetLastError();
		return rt;
	}
	retcode_t TCPSocket::Bind()
	{
		retcode_t rt = SUCCESS;
		if( ::bind(m_socket,(SA*)&m_addr,sizeof(m_addr)) == SOCKET_ERROR )
			rt = GetLastError();
		return rt;
	}
	retcode_t TCPSocket::Listen()
	{
		retcode_t rt = SUCCESS;
		if( ::listen(m_socket,FD_SETSIZE) == SOCKET_ERROR )
			rt = GetLastError();
		return rt;
	}
	socket_t TCPSocket::Accept()
	{
		socketlen_t len = sizeof(m_addr);
		return ::accept(m_socket,(SA*)&m_addr,&len);
	}
}
